const express = require("express");
const cors = require("cors");
const app = express();
const { secretKey } = require("./config");
const expressJWT = require("express-jwt");
const multer = require("multer")
//跨域
app.use(cors());

//post请求
app.use(express.json());
app.use(express.urlencoded());

//挂载登录注册路由
const userRouter = require("./router/user");
app.use("/user", userRouter);

const path = require("path")

// 挂载静态文件
// app.use('/api', express.static('/uploads'))


/* app.use(
  expressJWT({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: ["/register", "/login", /^\/uploads\//],
  })
); */


//上传头像文件
const avatarRouter = require("./router/avatar");
app.use("/api", avatarRouter);

// 优惠卷信息
const couponRouter = require("./router/coupon")
app.use("/api",couponRouter)



const Joi = require("joi");
//错误中间件
app.use(function (err, req, res, next) {
  // 4.1 Joi 参数校验失败
  if (err instanceof Joi.ValidationError) {
    return res.send({
      status: 1,
      message: err.message,
    });
  }

  if (err instanceof multer.MulterError) {
    return res.send({
      status: 1,
      message: '文件上传报错',
      type: err.message
    });
  } 
  // 4.2 未知错误
  res.send({
    status: 101,
    message: err.message,
  });
});

app.listen(3000, () => {
  console.log("3000 running");
});
